package com.ruoyi.common.utils.bean;

import org.apache.commons.text.WordUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/** @author Haokun 上下文获取bean */
@Component
public class ApplicationContextUtils implements ApplicationContextAware {

  private static ApplicationContext context;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    ApplicationContextUtils.context = applicationContext;
  }

  public static ApplicationContext getContext() {
    return context;
  }

  public static Object getBean(String beanName) {
    return context.getBean(beanName);
  }

  public static <T> T getBean(String beanName, Class<T> requiredType) {
    return context.getBean(beanName, requiredType);
  }

  public static <T> T getBean(Class<T> requiredType) {
    String simpleName = requiredType.getSimpleName();
    String name = WordUtils.uncapitalize(simpleName);

    T obj = null;
    try {
      obj = getBean(name, requiredType);
    } catch (NoSuchBeanDefinitionException e) {
    }

    if (obj != null) {
      return obj;
    }

    return context.getBean(requiredType);
  }
}
